/*
 * Data stores
 */
var searchContactStore;
var searchDateStart;
var searchDateEnd;
var searchMembers;
var searchMemberStore;

var getContactDataObj = {
	getContactsForGrid : function(viewPort,start,limit,sort,acdc,paging,searchString) {
		/*
		 * Set contactLogStart
		 */
		$('contactLogStart').value = start;
		var params = 'handler=getContactsForGrid&viewPort='+viewPort+'&start='+start+'&limit='+limit+'&sort='+sort+'&acdc='+acdc+'&paging='+paging+'&searchString='+searchString;
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport) {
				updateStatus('','clearStatus','contactWindowStatus');
				var returnString = transport.responseText;
				var stringArray = returnString.split('~~|~~');
				if (stringArray[1] == 0) {
					$('messageSearch').className = 'errorMessageBig';
					$('messageSearch').innerHTML = 'Your search did not return any results.';
					$('messageSearch').style.display = '';
				} else {
					getContactDataObj.renderContactsToWindow(transport.responseText);
					$('messageSearch').style.display = 'none';
				}			
			},
			onFailure: function() {
				alert('Oops!');
			}			
		});
		updateStatus('Loading contacts...','wait','contactWindowStatus');
	},
	renderContactsToWindow : function(returnString) {		
		var stringArray = returnString.split('~~|~~');
		var viewPort    = stringArray[0];
		var stringJSON  = stringArray[1];
		var jsonObject = stringJSON.evalJSON();
		var rowClass = '';
		
		var totalContacts = jsonObject.TotalRows;
		var returnedRows  = ((jsonObject.Contacts.length)-1);
		var totalPages    = jsonObject.TotalPages;
		var logTitle      = jsonObject.LogTitle;
		var start         = parseInt(jsonObject.Start);
		var limit         = parseInt(jsonObject.Limit);
		var sort          = jsonObject.Sort;
		var acdc          = jsonObject.AcDc;
		var origAcDc      = jsonObject.OrigAcDc;
		var currentPage   = jsonObject.CurrentPage;
		var searchString  = jsonObject.SearchString;
		
		var prevStart = parseInt(start-limit);
		var nextStart = parseInt(start+limit);
		if (totalContacts>0) {
			$('contactLogTitle').innerHTML = logTitle;
			$('contactLogLoaded').value = 1;
			
			var navTab = '<table style="margin: 6px 0 0 5px;">' +
						 '<tr><td style="width: 17px; padding: 3px;">';
			if (prevStart<0) {
				navTab += '<img src="images/button_prev_off.gif" />';
			} else {
				navTab += '<a href="#" onClick="getContactDataObj.getContactsForGrid(\'page\','+prevStart+','+limit+',\''+sort+'\',\''+origAcDc+'\',0,\''+searchString+'\'); return false;" title="Previous Page">' +
						  '<img src="images/button_prev.gif" style="border: none;" alt="Previous Page"></a>';
			}
				navTab += '</td>';
				
			if (totalPages>1) {
				navTab += '<td>';
				navTab += '<select id="navPages" size="1" onChange="getContactDataObj.getContactsForGrid(\'page\',this.options[this.selectedIndex].value,'+limit+',\''+sort+'\',\''+origAcDc+'\',0,\''+searchString+'\'); return false;" style="width: 50px;">';
				for(a=1;a<=totalPages;a++) {
					var value = parseInt(a*20)-20;
					navTab += '<option value="'+value+'"';
					if (currentPage == a) {
						navTab += ' selected ';
					}
					navTab += '>'+a+'</option>';
				}
				navTab += '</select>';
				navTab += '</td>';
			}
				
				navTab += '<td style="width: 17px; padding: 3px;">';
			if (nextStart>totalContacts) {
				navTab += '<img src="images/button_next_off.gif" />';
			} else {
				navTab += '<a href="#" onClick="getContactDataObj.getContactsForGrid(\'page\','+nextStart+','+limit+',\''+sort+'\',\''+origAcDc+'\',0,\''+searchString+'\'); return false;" title="Next Page">' +
						  '<img src="images/button_next.gif" style="border: none;" alt="Next Page"></a>';
			}			 
				navTab += '</td><td style="margin-left: 10px; padding: 3px;">';
				navTab += '<input type="text" id="contactSearchBox" style="width: 100px;" /></td>';
				navTab += '<td style="padding: 3px;"><a href="#" onClick="searchContactsObj.toggleAdvancedSearchForm(); return false;" title="Advanced search"><img src="images/buttonAdvancedSearch.gif" style="border: none;" alt="Advanced search" /></a></td>';
				navTab += '</tr></table>';
			
			$('gridNavTab').innerHTML = navTab;	
			$('gridNavTab').style.display = '';
							
			var stringOut = '<table class="dataTable" style="font-size: 1em;">';
			stringOut    += '<tr>';
			
			if (viewPort == 'page') {
				stringOut += '<th style="width: 5%;"></th>';
			}
			
			stringOut    +=	'<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" onClick="getContactDataObj.getContactsForGrid(\'page\','+start+','+limit+',\'C.IDNumber\',\''+acdc+'\',0,\''+searchString+'\'); return false;" style="width: 5%; text-align: right;"><div ext:qtip="Sort by Contact ID #" style="cursor: pointer;">ID #</div></th>' + 
							'<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" onClick="getContactDataObj.getContactsForGrid(\'page\','+start+','+limit+',\'C.SubjectLine\',\''+acdc+'\',0,\''+searchString+'\'); return false;" style="width: 45%;"><div ext:qtip="Sort by Subject" style="cursor: pointer;">Subject</div></th>';
			
			if (viewPort == 'page') {
				stringOut += '<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" onClick="getContactDataObj.getContactsForGrid(\'page\','+start+','+limit+',\'S.StaffLName\',\''+acdc+'\',0,\''+searchString+'\'); return false;" style="width: 20%;"><div ext:qtip="Sort by Staff" style="cursor: pointer;">Staff</div></th>';
			}				
							
			stringOut    += '<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" onClick="getContactDataObj.getContactsForGrid(\'page\','+start+','+limit+',\'C.DateofContact\',\''+acdc+'\',0,\''+searchString+'\'); return false;" style="width: 10%;"><div ext:qtip="Sort by Entry Date" style="cursor: pointer;">Date Entered</div></th>';
			
			if (viewPort == 'page') {
				stringOut+= '<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" onClick="getContactDataObj.getContactsForGrid(\'page\','+start+','+limit+',\'C.DateofClosure\',\''+acdc+'\',0,\''+searchString+'\'); return false;" style="width: 10%;"><div ext:qtip="Sort by Closure Date" style="cursor: pointer;">Date Closed</div></th>';
			}
							
			stringOut    +=	'<th onmouseover="this.className=\'thHover\';" onmouseout="this.className=\'\';" onClick="getContactDataObj.getContactsForGrid(\'page\','+start+','+limit+',\'C.Status\',\''+acdc+'\',0,\''+searchString+'\'); return false;" style="width: 5%; text-align: center;"><div ext:qtip="Sort by Status" style="cursor: pointer;">Status</div></th></tr>';
				
			for(a=0;a<=returnedRows;a++) {
				var entryID          = jsonObject.Contacts[a].ContactID;
				var contactID        = jsonObject.Contacts[a].IDNumber;
				var contactDateEntry = jsonObject.Contacts[a].DateofContact;
				var contactDateClosed= jsonObject.Contacts[a].DateofClosure;
				var contactSubject   = jsonObject.Contacts[a].SubjectLine;
				var contactStatus    = jsonObject.Contacts[a].Status;
				var contactFollowUp  = jsonObject.Contacts[a].ReferralFollowUp;
				var staffNameFirst   = jsonObject.Contacts[a].StaffFName;
				var staffNameLast    = jsonObject.Contacts[a].StaffLName;
				var staffEmail       = jsonObject.Contacts[a].StaffEmail;
				var staffPhone       = jsonObject.Contacts[a].StaffPhone;
				var statusClass      = jsonObject.Contacts[a].StatusClass;
				var statusText       = jsonObject.Contacts[a].StatusText;
				var statusRowClass   = jsonObject.Contacts[a].StatusRowClass;
				
				var staffFullName = staffNameFirst+' '+staffNameLast;
				var staffContactString = staffFullName+'<br />'+staffEmail+'<br />Ph: '+staffPhone;
				/*
				 * Check for subject string length if we're in window mode
				 */
				if ( (viewPort != 'page') && (contactSubject.length>40) ) {
					contactSubjectDisplay = contactSubject.substr(0,40)+'...';
				} else {
					contactSubjectDisplay = contactSubject;
				}
				
				if ((a % 2) > 0) { 
					rowClass = 'altRow'; 
				} else { 
					rowClass = '';
				}			
				
				if (statusRowClass == 'statusAlertRow') {
					rowClass = statusRowClass;
				}
				
				stringOut += '<tr id="contactRow'+entryID+'" class="'+rowClass+'">';
				if (viewPort == 'page') {
					stringOut += '<td style="text-align: center;">';
					stringOut += ' <a href="#" onClick="trashUpdateObj.sendToTrash(\''+entryID+'\',\'contact\'); return false;" title="Delete this contact"><img src="images/buttonDeleteBig.gif" style="border: none;" alt="Delete" /></a>';
					stringOut += ' <a href="#" onClick="contactStatusUpdateObj.contactCloseFromRow('+entryID+',\''+rowClass+'\'); return false;" title="Close this contact"><img src="images/buttonCloseBig.gif" style="border: none;" alt="Close this contact" /></a></td>';
				}
				
				stringOut += '<td style="text-align: right;">'+contactID+'</td>';
				stringOut += '<td ext:qtip="'+contactSubject+'"><a href="#" onClick="viewTabContent.viewContactInit('+entryID+'); return false;">'+contactSubjectDisplay+'</a></td>';
				
				if (viewPort == 'page') {
					stringOut += '<td><a ext:qtip="'+staffContactString+'" href="mailto:'+staffEmail+'">'+staffFullName+'</a></td>';
				}
				
				stringOut += '<td>'+contactDateEntry+'</td>';
				
				if (viewPort == 'page') {
					stringOut += '<td>'+contactDateClosed+'</td>';
				}
							 
				stringOut += '<td id="statusCell'+entryID+'"><div ext:qtip="'+statusText+'" class="'+statusClass+'"></div>' +
							 '</td></tr>';
				
			}		
			
			stringOut += '</table>';
		} else {
			stringOut = '';
		}
		$('windowContactsContainer').innerHTML = stringOut;
		
		// Init autocompleter field
		searchContactsObj.searchContacts();
	}
}

var getNoteDataObj = {
	getNotesForContact : function(contactID) {
		var params = 'handler=getMessages&itemID=' + contactID + '&type=contact';
			
		var ajaxResults = new Ajax.Request('ajaxDirector.php', {
			method: 'POST',
			parameters: params,
			onSuccess: function(transport){
				getNoteDataObj.renderNotes(transport.responseText);
			}
		});
	},
	renderNotes : function(stringJSON) {
		var jsonObject = stringJSON.evalJSON();
		var rowClass = '';
		
		var totalNotes = (jsonObject.Notes.length)-1;
		
		if (totalNotes>=0) {			
			var stringOut  = '<p style="margin-top: 5px;"><b>Existing notes for this contact</b></p>';
			stringOut += '<table class="dataTable" style="font-size: 1em;">';
				
			for(a=0;a<=totalNotes;a++) {
				var noteID        = jsonObject.Notes[a].MessageID;
				var noteDateEntry = jsonObject.Notes[a].DateEntry;
				var noteText      = jsonObject.Notes[a].Message;
				var staffFName    = jsonObject.Notes[a].StaffFName;
				var staffLName    = jsonObject.Notes[a].StaffLName;
				var staffEmail    = jsonObject.Notes[a].StaffEmail;
				var staffPhone    = jsonObject.Notes[a].StaffPhone;
				var staffUserid   = jsonObject.Notes[a].Userid;
				
				if ((a % 2) > 0) { 
					rowClass = 'altRow'; 
				} else { 
					rowClass = '';
				}			
				
				var staffFullName = staffFName+' '+staffLName;
				var staffContactString = staffFullName+'<br />'+staffEmail+'<br />Ph: '+staffPhone;
				
				
				stringOut += '<tr class="'+rowClass+'"><td><b>'+noteDateEntry+'</b> <a href="mailto:'+staffEmail+'" ext:qtip="'+staffContactString+'">'+staffFullName+'</a><br />'+noteText+'</td></tr>';
				
			}		
			
			stringOut += '</table>';
		} else {
			stringOut = '';
		}
		$('displayNotes').innerHTML = stringOut;
	}
}

var searchContactsObj = {
	searchContacts : function() {
		searchContactStore = new Ext.data.Store({
		    proxy: new Ext.data.HttpProxy({
				url: 'ajaxDirector.php?handler=getContactForAutocompleter'
		    }),
			    reader: new Ext.data.JsonReader({
	            root: 'Contacts',
	            totalProperty: 'Total',
	            id: 'ContactID'
	        }, [
	            {name: 'SubjectLine', mapping: 'SubjectLine'},
	            {name: 'ContactID', mapping: 'ContactID'},
	            {name: 'DateofContact', mapping: 'DateofContact'}
	        ])
    	});
    	var resultTpl = new Ext.XTemplate(
	        '<tpl for="."><div class="search-item">',
	            '<span>{SubjectLine} <b>{DateofContact}</b></span>',
	        '</div></tpl>'
	    );    
	    var search = new Ext.form.ComboBox({
	        store:        searchContactStore,
	        displayField: 'SubjectLine',
	        typeAhead:    false,
	        loadingText:  '<p><img src="images/wait.gif"> <b>Searching...</b></p>',
	        width:        110,
	        hideTrigger:  true,
	        tpl:          resultTpl,
	        applyTo:      'contactSearchBox',
	        itemSelector: 'div.search-item',
	        resizable:     true,
	        shadow:        false,
	        grow:          true,
	        growMax:       300,
	        growMin:       150,
	        listWidth:     400,
	        listAlign:     'tr-br',
	        emptyText:     'Quick search...',
	        handleHeight:  12,
	        onSelect: function(record){ 
	        	search.collapse();
	        	viewTabContent.viewContactInit(record.data.ContactID);
	         }
	    });	    
	},
	toggleAdvancedSearchForm : function() {
		$('messageSearch').style.display = 'none';
		if ($('formAdvancedSearch').style.display == '') {
			/*
			 * Close form
			 */
			this.clearAdvancedSearchForm();
			new Effect.SlideUp('formAdvancedSearch', {direction: 'top', duration: .2});
		} else {
			/*
			 * Open form
			 */
			new Effect.SlideDown('formAdvancedSearch', {direction: 'top', duration: .2});
			this.searchFormInit();			
		}
	},
	advancedContactSearch : function() {
		var keyword      = $F('sKeyword');
		var memberID     = $F('sMemberID');
		var dateStart    = $F('searchDateFieldStart'); 
		var dateEnd      = $F('searchDateFieldEnd'); 
		
		if (dateStart == 'Start') {
			dateStart = '';
		}
		if (dateEnd == 'End') {
			dateEnd = '';
		}
		
		if (
			keyword   == '' &&
			memberID  == '' &&
			dateStart == '' &&
			dateEnd   == ''
			) {
			var searchString = '';			
		} else {		
			var searchString = keyword+'|'+memberID+'|'+dateStart+'|'+dateEnd;
		}	
		getContactDataObj.getContactsForGrid('page',0,20,0,0,0,searchString);
	},
	returnAdvancedContactSearch : function() {
		
	},
	searchFormInit : function() {			
		if (!searchDateStart) {
			searchDateStart = new Ext.form.DateField({
				width: 200,
			    allowBlank: true,
			    format: 'm/d/Y',
			    emptyText: "Start",
				applyTo: 'searchDateFieldStart'
			});
		}
		if (!searchDateEnd) {
			searchDateEnd = new Ext.form.DateField({
				width: 200,
			    allowBlank: true,
			    format: 'm/d/Y',
			    emptyText: "End",
				applyTo: 'searchDateFieldEnd'
			});		
		}
		searchMemberStore = new Ext.data.Store({
		    proxy: new Ext.data.HttpProxy({
				url: 'ajaxDirector.php?handler=getMembersForExtAutocompleter'
		    }),
			    reader: new Ext.data.JsonReader({
	            root: 'Members',
	            totalProperty: 'Total',
	            id: 'MemberID'
	        }, [
	            {name: 'MemberID', mapping: 'MemberID'},
	            {name: 'MemberFullName', mapping: 'MemberFullName'},
	            {name: 'City', mapping: 'City'},
	            {name: 'State', mapping: 'State'}
	        ])
    	});
    	var resultTpl = new Ext.XTemplate(
	        '<tpl for="."><div class="search-item">',
	            '<span><b>{MemberFullName}</b> {City} {State}</span>',
	        '</div></tpl>'
	    );    
	    if (!searchMembers) {
		    searchMembers = new Ext.form.ComboBox({
		    	id:           'sMemberIDCombo',
		    	hiddenName:   'sMemberID',
		        store:        searchMemberStore,
		        displayField: 'MemberFullName',
		        valueField:   'MemberID',
		        typeAhead:    false,
		        loadingText:  '<p><img src="images/wait.gif"> <b>Searching...</b></p>',
		        width:        400,
		        hideTrigger:  true,
		        tpl:          resultTpl,
		        applyTo:      'sMemberName',
		        itemSelector: 'div.search-item',
		        shadow:        false,
		        listWidth:     400
		    });
	    }		    
	},
	clearAdvancedSearchForm : function() {
		
	}
}
